package common.kingdee.repository;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.PrivateKey;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;

import common.tools.AppException;
import common.tools.RSAUtils;
public class KingdeeEncrypt {
	public String encrypt(String data,String keyFileNamePath) {
		try {			
			byte[] b = FileUtils.readFileToByteArray(new File(keyFileNamePath));
			PrivateKey restorePublicKey = RSAUtils.restorePrivateKey(b);
			byte[] bytes = Base64.encodeBase64(RSAUtils.encryptLargerDefined(data.getBytes("utf-8"), restorePublicKey));
			return new String(bytes, "UTF-8");
		} catch (FileNotFoundException e) {
			throw new AppException("没有找到密钥文件"+keyFileNamePath);
		} catch (IOException e) {
			throw new AppException("无法正常读取密钥文件"+keyFileNamePath);
		} catch (Exception e) {
			throw new AppException("解密出错，请确认密钥文件"+keyFileNamePath+"的有效性,错误详情："+e.getMessage());
		}
	}

/*	private String buildFilePath(String rootPath,String path,String keyFile) {
		if(rootPath.endsWith("lib/")){//在lib路径下
			rootPath=rootPath.substring(0, rootPath.lastIndexOf("lib/"));
		}else if(rootPath.endsWith("classes/")){//在classes路径下
			rootPath=rootPath.substring(0, path.lastIndexOf("classes/"));
		}
		if(path==null||path.trim().equals("/")||path.trim().equals("")){
			return rootPath+ keyFile;
		}else{
			if(!path.endsWith("/")){
				path+="/";
			}
			if(path.startsWith("/")){
				path=path.substring(1);
			}
			return rootPath+path + keyFile;
		}
	}*/
}
